package com.xdxc.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理所有未捕获的异常
     *
     * @param ex      异常对象
     * @param request Web请求对象
     * @return 统一格式的响应实体
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleAllExceptions(Exception ex, WebRequest request) {
        Map<String, Object> response = new HashMap<>();
        response.put("data", new HashMap<>());
        response.put("msg", "服务器异常");
        response.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());

        // 可选：记录日志
        ex.printStackTrace();

        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 处理特定类型的异常（例如自定义异常）
     *
     * @param ex      自定义异常对象
     * @param request Web请求对象
     * @return 统一格式的响应实体
     */
    @ExceptionHandler(BizException.class)
    public ResponseEntity<Map<String, Object>> handleCustomException(BizException ex, WebRequest request) {
        Map<String, Object> response = new HashMap<>();
        response.put("data", new HashMap<>());
        response.put("msg", ex.getMessage());
        response.put("code", ex.getCode());

        // 可选：记录日志
        ex.printStackTrace();

        return new ResponseEntity<>(response, HttpStatus.valueOf(ex.getCode()));
    }
}

/**
 * 自定义异常类示例
 */
